//
//  DYIMModule.m
//  HBuilder
//
//  Created by 黄德玉 on 2019/11/2.
//  Copyright © 2019 DCloud. All rights reserved.
//

#import "DYIMModule.h"
#import "WXUtility.h"
#import <RongIMKit/RongIMKit.h>
#import "AppDelegate.h"
#import "DYChatViewController.h"
#import "MJExtension.h"
#import "EBHUserInfoModel.h"
#import "EBHUserManager.h"

@interface DYIMModule()<RCIMReceiveMessageDelegate,RCIMUserInfoDataSource>

@property (nonatomic, copy) WXModuleKeepAliveCallback newMsgBlock; //聊天室的回调
@property (nonatomic, strong)  WXModuleKeepAliveCallback  mesListBlock; // 聊天列表回调

@end

@implementation DYIMModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(login:callback:))
WX_EXPORT_METHOD(@selector(startTalk:))
WX_EXPORT_METHOD(@selector(userInfo:callback:))

WX_EXPORT_METHOD(@selector(joinChatRoom:callback:))
WX_EXPORT_METHOD(@selector(quitChatRoom:callback:))
WX_EXPORT_METHOD(@selector(sendMessage:callback:))
WX_EXPORT_METHOD(@selector(getChatRoomMsg:callback:))
WX_EXPORT_METHOD(@selector(getMsgList:callback:))
WX_EXPORT_METHOD(@selector(getChatMsg:callback:))


#pragma mark - Export Method

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)userInfo:(NSString *)options callback:(WXModuleKeepAliveCallback)callback{
    NSDictionary * userInfo = [self dictionaryWithJsonString:options];
    if (userInfo) {
        [[EBHUserManager sharedManager] loginWithUserInfo:userInfo];
    }
    if (callback) {
        callback(@"登录成功",YES);
    }
}

- (void)login:(NSDictionary *)options callback:(WXModuleKeepAliveCallback)callback{
    if ([[RCIM sharedRCIM] getConnectionStatus] == ConnectionStatus_Connected)  {
        if (callback) {
            callback(@"已经成功连接im",YES);
        }
        return;
    }
    NSDictionary * dic = options;
    if ([options isKindOfClass:[NSString class]]) {
        dic = [self dictionaryWithJsonString:(NSString *)options];
    }
    
    NSString * token = [dic objectForKey:@"token"];
    NSString * userName = [EBHUserManager sharedManager].userInfo.name;
    if (!userName) {
        userName  = @"无名";
    }
    NSString * avatar = [EBHUserManager sharedManager].userInfo.avatar;
    if (!avatar) {
        avatar = @"https://b-ssl.duitang.com/uploads/item/201806/07/20180607185957_fjrFt.thumb.700_0.jpeg";
    }
    if (!token) {
        callback(@"登录IM失败",YES);
        return;
    }
    __weak typeof(self)weakSelf = self;
    [[RCIM sharedRCIM] connectWithToken:token  success:^(NSString *userId) {
        RCUserInfo *_currentUserInfo =
               [[RCUserInfo alloc] initWithUserId:userId name:userName portrait:avatar];
        [RCIM sharedRCIM].currentUserInfo = _currentUserInfo;
        [[RCIM sharedRCIM] setEnableMessageAttachUserInfo:YES];
        [RCIM sharedRCIM].userInfoDataSource = self;
        if (callback) {
            callback(@"登录im成功",YES);
        }
    } error:^(RCConnectErrorCode status) {
        if (callback) {
                   callback(@"登录im失败",YES);
        }
    } tokenIncorrect:^{
        if (callback) {
                   callback(@"登录im失败",YES);
        }
    }];
}

- (void)startTalk:(NSString *)talk{
    NSDictionary * dic = [self dictionaryWithJsonString:talk];
    NSString * targetID = [dic objectForKey:@"targetId"];
    NSString * name = [dic objectForKey:@"name"];
    NSString * avatar = [dic objectForKey:@"avatar"];
    NSInteger  status = [[dic objectForKey:@"status"] integerValue];
    NSInteger  countDown = [[dic objectForKey:@"expiryDate"] integerValue];
    
    [[EBHUserManager sharedManager] updateTargetUserInfo:name avatar:avatar targetId:targetID];
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:0];
    
    DYChatViewController * vc = [[DYChatViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:targetID];
    vc.ebh_userName = name;
    vc.ebh_CountDown = countDown;
    vc.ebh_status = status;
    UINavigationController * nav = (UINavigationController *)(AppDelegate *)[UIApplication sharedApplication].delegate.window.rootViewController;
    [nav pushViewController:vc animated:YES];
    __weak typeof(self)weakSelf = self;
    vc.didPopBlock = ^{
        if (weakSelf.mesListBlock) {
              weakSelf.mesListBlock(@"Success", YES);
          }
    };
}


- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *userInfo))completion{

    if ([userId isEqualToString:[EBHUserManager sharedManager].userInfo.id]) {
        // 自己
        RCUserInfo *user = [[RCUserInfo alloc]init];
        user.userId = userId;
        user.name = [EBHUserManager sharedManager].userInfo.name;
        user.portraitUri = [EBHUserManager sharedManager].userInfo.avatar;
        NSLog([user.name stringByAppendingString:@"IM 获取头像"]);
        return completion(user);
    }else{
        // 对方
        RCUserInfo *user = [[RCUserInfo alloc]init];
        user.userId = userId;
        user.name = [EBHUserManager sharedManager].targetUserInfo.name;
        user.portraitUri = [EBHUserManager sharedManager].targetUserInfo.avatar;
        NSLog([user.name stringByAppendingString:@"IM 获取头像"]);
        return completion(user);
    }
}

- (void)joinChatRoom:(NSString *)str callback:(WXModuleKeepAliveCallback)callback{
    NSDictionary * dic = [self dictionaryWithJsonString:str];
    NSString * roomId = [dic objectForKey:@"roomId"];
    [[RCIMClient sharedRCIMClient] joinChatRoom:roomId messageCount:50 success:^{
        if (callback) {
            callback(@"success",YES);
        }
    } error:^(RCErrorCode status) {
        if (callback) {
            callback(@"failure",YES);
        }
    }];
}

- (void)quitChatRoom:(NSString *)str callback:(WXModuleKeepAliveCallback)callback{
    NSDictionary * dic = [self dictionaryWithJsonString:str];
    NSString * roomId = [dic objectForKey:@"roomId"];
    [[RCIMClient sharedRCIMClient] quitChatRoom:roomId success:^{
        if (callback) {
           callback(@"success",YES);
        }
    } error:^(RCErrorCode status) {
        if (callback) {
           callback(@"failure",YES);
        }
    }];
}

- (void)sendMessage:(NSString *)str callback:(WXModuleKeepAliveCallback)callback{
    NSDictionary * dic = [self dictionaryWithJsonString:str];
    NSString * roomId = [dic objectForKey:@"roomId"];
    NSString * msg = [dic objectForKey:@"message"];
    
    RCTextMessage * rctMsg = [RCTextMessage messageWithContent:msg];

    [[RCIMClient sharedRCIMClient] sendMessage:ConversationType_CHATROOM targetId:roomId content:rctMsg pushContent:nil pushData:nil option:nil success:^(long messageId) {
        if (callback) {
            callback(@"success",YES);
        }
    } error:^(RCErrorCode nErrorCode, long messageId) {
        if (callback) {
            callback(@"failure",YES);
        }
    }];
}

- (void)getChatRoomMsg:(NSString *) str callback:(WXModuleKeepAliveCallback)callback{
    self.newMsgBlock = callback;
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
}

- (void)getChatMsg:(NSString *) str callback:(WXModuleKeepAliveCallback)callback{
    self.mesListBlock = callback;
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
}


- (void)getMsgList:(NSString *)str callback:(WXModuleKeepAliveCallback)callback{
    static NSInteger num = 0;
    NSArray * arr = [[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]];
    NSMutableArray * jsonContent = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(RCConversation * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        NSString * avatar = obj.lastestMessage.senderUserInfo.portraitUri;
        if (!avatar) {
            avatar = @"";
        }
        [dic setObject:avatar forKey:@"avatar"];
        
        NSString * name = obj.lastestMessage.senderUserInfo.name;
        if (!name) {
            name = @"";
        }
        [dic setObject:name forKey:@"name"];
        
        NSInteger unreadMessageCount = obj.unreadMessageCount;
        num = num + unreadMessageCount;
        
        [dic setObject:@(unreadMessageCount) forKey:@"unreadMessageCount"];
        NSString * idf = obj.targetId;
        if ([idf isEqualToString:[EBHUserManager sharedManager].userInfo.id]) {
            idf = obj.senderUserId;
        }
        if (!idf) {
            idf = @"";
        }
        [dic setObject:idf forKey:@"id"];
        
        id msgContent = obj.lastestMessage;
        //文本消息
        if ([msgContent isKindOfClass:[RCTextMessage class]]) {
            RCTextMessage * textMsg = msgContent;
            NSString * content  = textMsg.content;
            if (!content) {
                content = @"";
            }
            [dic setObject:content forKey:@"msgContent"];
            [dic setObject:@1 forKey:@"type"];
        }
        if ([msgContent isKindOfClass:[RCLocationMessage class]]) {
            [dic setObject:@"[定位]" forKey:@"msgContent"];
            [dic setObject:@4 forKey:@"type"];
        }
        if ([msgContent isKindOfClass:[RCImageMessage class]]) {
            [dic setObject:@"[图片]" forKey:@"msgContent"];
            [dic setObject:@2 forKey:@"type"];
        }
        if ([msgContent isKindOfClass:[RCVoiceMessage class]]) {
            [dic setObject:@"[语音]" forKey:@"msgContent"];
            [dic setObject:@3 forKey:@"type"];
        }
        if ([msgContent isKindOfClass:[RCRichContentMessage class]]) {
            [dic setObject:@"[图文]" forKey:@"msgContent"];
            [dic setObject:@1 forKey:@"type"];
        }
        
        [jsonContent addObject:dic];
    }];
    
//    UIApplication *application = [UIApplication sharedApplication];
//    [application setApplicationIconBadgeNumber:num];
//    num = 0;
    
  NSString *strJson = [jsonContent mj_JSONString];
    if (callback) {
        callback(strJson,YES);
    }
}

#pragma mark - msg

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left{
    NSString * jsonStr = [message mj_JSONString];
    if (message.conversationType == ConversationType_PRIVATE) {
        if (self.mesListBlock) {
            self.mesListBlock(@"SUCCESS", YES);
        }
    } else if(message.conversationType == ConversationType_CHATROOM){
        if (self.newMsgBlock) {
           self.newMsgBlock(jsonStr, YES);
        }
    }
}



- (void)showAlertWithMsg:(NSString *)msg {
    
}


@end
